package com.dykj.fireFighting.server.socialUnit.occupiedvideo.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dykj.fireFighting.api.base.video.vo.VideoPlayVo;
import com.dykj.fireFighting.api.socialUnit.dutymanger.entity.DutyRecord;
import com.dykj.fireFighting.api.socialUnit.occupiedvideo.dto.OccupiedVideoDto;
import com.dykj.fireFighting.api.socialUnit.occupiedvideo.entity.OccupiedVideo;
import com.dykj.fireFighting.api.socialUnit.occupiedvideo.service.IOccupiedVideoService;
import com.dykj.fireFighting.api.socialUnit.occupiedvideo.vo.OccupiedVideoPlayVo;
import com.dykj.fireFighting.common.core.service.impl.BaseServiceImpl;
import com.dykj.fireFighting.common.core.utils.HttpClientResult;
import com.dykj.fireFighting.common.core.utils.HttpUtil;
import com.dykj.fireFighting.common.core.vo.PageVo;
import com.dykj.fireFighting.common.starter.redis.service.RedisService;
import com.dykj.fireFighting.server.socialUnit.occupiedvideo.mapper.OccupiedVideoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 救援场地和消防车通道占用情况
 *
 * @Author zly
 * @Date  2021-07-20 10:17:37
 */
@Slf4j
@DubboService
@Transactional(rollbackFor = Exception.class)
public class OccupiedVideoServiceImpl extends BaseServiceImpl<OccupiedVideoMapper, OccupiedVideo> implements IOccupiedVideoService {

    @Autowired
    private RedisService redisService;

    @Value("${YS.HOSTADDRESS}")
    private String hostAddress;
    @Value("${YS.DEVONLY}")
    private String devonly;

    @Override
    public OccupiedVideoPlayVo videoPlay(String id) {

        OccupiedVideo occupiedVideo = this.baseMapper.selectById(id);
        String accessToken = getAccessToken(occupiedVideo.getVideoSerial(), occupiedVideo.getAppkey(), occupiedVideo.getAppsecret());

        OccupiedVideoPlayVo videoPlayVo = new OccupiedVideoPlayVo();
        videoPlayVo.setVideoSerial(occupiedVideo.getVideoSerial());
        videoPlayVo.setChannel(occupiedVideo.getChannel());
        videoPlayVo.setAccessToken(accessToken);

        videoPlayVo.setUserName(occupiedVideo.getUserName());
        videoPlayVo.setPassword(occupiedVideo.getPassword());
        videoPlayVo.setIp(occupiedVideo.getIp());
        videoPlayVo.setPort(occupiedVideo.getPort());
        videoPlayVo.setVedioType(occupiedVideo.getVedioType());
        videoPlayVo.setId(occupiedVideo.getId());
        return videoPlayVo;

    }

    @Override
    public PageVo<OccupiedVideo> queryList(OccupiedVideoDto occupiedVideoDto) {
        HashMap<String , Object> params = new HashMap<>(16);
        String videoName = occupiedVideoDto.getVideoName();
        params.put("videoName",videoName);
        params.put("unitId",occupiedVideoDto.getUnitId());

        params.put("vedioType",occupiedVideoDto.getVedioType());
        params.put("isOccupied",occupiedVideoDto.getIsOccupied());
        Page page = new Page();
        // 设置当前页码
        page.setCurrent(occupiedVideoDto.getPage());
        // 设置页大小
        page.setSize(occupiedVideoDto.getLimit());
        return new PageVo<OccupiedVideo>(this.baseMapper.queryList(page,params));
    }

    /**
     * 获取AccessToken 并设置redis值
     *
     * @param gridCode
     * @return
     */
    public String getAccessToken(String gridCode, String appKey, String appSecret) {
        //从redis中获取token
        String accessToken = (String) redisService.get("AccessToken_" + gridCode);
        if (StringUtils.isBlank(accessToken)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("appKey", appKey);
            params.put("appSecret", appSecret);
            HttpClientResult result = null;
            try {
                result = HttpUtil.postWithForm(hostAddress, null, params);
                if (!result.isSuccess()) {
                    log.error("{}调用发生异常,result:{}", hostAddress, result);
                } else {
                    if (StringUtils.isNotBlank(result.getData())) {
                        String res = result.getData().substring(result.getData().indexOf("{"));
                        JSONObject resultObj = JSONUtil.parseObj(res);
                        String code = (String) resultObj.get("code");
                        String msg = (String) resultObj.get("msg");
                        if ("200".equals(code)) {
                            JSONObject dataObj = JSONUtil.parseObj(resultObj.get("data"));
                            accessToken = (String) dataObj.get("accessToken");
                            Long expireTime = (Long) dataObj.get("expireTime");
                            Long now = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
                            // 有效期 = 过期时间 - 现在 - 一天
                            //Long expire = (expireTime - now - (60 * 60 * 24 * 1000)) / 1000;
                            Long expire = 259200L;
                            // 普通缓存放入并设置时间
                            redisService.set("AccessToken_" + gridCode, accessToken, expire);
                        } else {
                            log.info("返回码：" + code);
                            log.info("返回信息：" + msg);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return accessToken;
    }
}
